class QiniuService
  include Serviceable
  include StatusObject

  def initialize(filePath, file_name, obj)
    @filePath = filePath
    @bucket = 'songli'
    @file_name = file_name
    @obj = obj
    @digest = OpenSSL::Digest.new('sha1')
  end

  def call
    set_file_name
    put_policy = Qiniu::Auth::PutPolicy.new(@bucket, @key, 3600)
    uptoken = Qiniu::Auth.generate_uptoken(put_policy)
    code, result, response_headers = Qiniu::Storage.upload_with_token_2(
                                       uptoken,
                                       @filePath,
                                       @key,
                                       nil,
                                       bucket: @bucket
                                      )
    if code == 200
      Rails.logger.info "状态的code是200"
      Status.new(success: true, notice: result)
    else
      raise  "Qiniu Upload failed, status code: #{code}, response: #{response_headers}"
      Status.new(success: false, notice: '失败')
    end
  end

  private
  def set_file_name
    upload_path = "uploads/store/#{store_id}/#{@obj.class.name.underscore}/#{@obj.id}"
    @key = "#{upload_path}/#{Digest::SHA256.hexdigest("#{set_random}")}.#{@file_name}"
  end

  def set_random
    timestamp = Time.now.to_i.to_s(:number)
    numero = timestamp + generate_random(6)
  end

  def generate_random(length)
    chars = Array(0..9)
    length.times.map { chars.sample }.join
  end

  def store_id
    if @obj.respond_to?(:store_id)
      @obj.store_id
    else
      @obj.id
    end
  end

end
